<?php

/**
 * Created by PhpStorm.
 * User: mofeng
 * Date: 16/9/5
 * Time: 上午10:37
 */

namespace App\Api\System\Controllers;

use App\Api\Auth\Models\UsersOpenId;
use App\Api\System\Models\QiniuPhotos;
use App\Http\Controllers\Controller;
use App\Libs\Wechat\WechatService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Qiniu\Auth;

class SystemController extends Controller
{

    public function logRequest(Request $request)
    {
        $params = $request->all();
        if (empty($params)) {
            info('callback content', [$request->header(), $request->getContent()]);
            return '';
        }
        \Log::info('request: ', $params);

        return $params;
    }

    public function uploadToken(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $bucket = data_get($params, 'bucket', '');
        info('用户获取了七牛上传凭证', $params);
        $c = new Auth('6qv-u0UcmzC8D0j3siOfeq_ZztQGap6YSaWfTIVE', 'RV0ioKFGqSDXiIASeDVMNCTUFGkeGkA6sxXbxgpq');
        //$returnBody = '{"fkey":"$(key)","type":"$(type)","uid":"'.$uid.'"}';
        $policy = array(
            'callbackUrl'  => env('APP_URL') . '/api/system/qiniu/callback', //'http://rocky.zhuopu.net:90/api/system/qiniu/callback',//
            'callbackBody' => 'fkey=$(key)&type=$(type)&source=$(source)&uid=' . data_get($user, 'id', '1') . '&source=' . data_get($params, 'source', '') . '&type_id=' . data_get($params, 'typeId', '') . '&shooting_time=' . data_get($params, 'shootingTime', '').'&bucket=' . data_get($params, 'bucket', '') ,
            //'callbackBody' => $returnBody,
        );

        $token = $c->uploadToken($bucket, null, 3600, $policy);
        info('callbackurl', $policy);
        return $this->formatOutput($token);
    }

    public function qiniuCallback(Request $request)
    {
        $params = $request->all();
        info('七牛文件上传回调参数', $params);
        $fkey  = data_get($params, 'fkey', '');
        $bucket  = data_get($params, 'bucket', '');
        switch ($bucket) {
            default:
                $url = 'https://cdnrenttest.relianchuanmei.com';
        }
        $uid   = data_get($params, 'uid', 0);
        $source = data_get($params, 'source', 0);
        $cloud_name = 'http://cdn.rockysports.cn/' . $fkey;
        //todo photo create
        QiniuPhotos::create([
            'type' => 1,
            'fkey' => $fkey,
            'bucket' => $bucket,
            'user_id' => $uid,
            'source' => $source,
        ]);
        return $this->formatOutput([
            'fkey' => $fkey,
            'url' => $url.'/'.$fkey,
        ]);
    }
    
    public function uploadFileToken(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $bucket = data_get($params, 'bucket', '');
        info('用户获取了七牛上传文件凭证', $params);
        $c = new Auth('ACgQc-uOm9-tEpALCkI5cdVjtTFiZIP7TOK6dITX', 'gr-MU1kpPkPh64GkbH4PTzr2NOsRnHT4vfG6Xpt2');
        //$returnBody = '{"fkey":"$(key)","type":"$(type)","uid":"'.$uid.'"}';
        $policy = array(
            'callbackUrl'  => env('APP_URL').'/api/system/qiniu/filecallback',//'http://rocky.zhuopu.net:90/api/system/qiniu/callback',//
            'callbackBody' => 'fkey=$(key)&type=$(type)&group_id=$(group_id)&uid='.data_get($user, 'id', '1').'&group_id='.data_get($params, 'gameId', '').'&type_id='.data_get($params,'typeId','').'&shooting_time='.data_get($params,'shootingTime',''),
            //'callbackBody' => $returnBody,
        );

        $token = $c->uploadToken($bucket, null, 3600, $policy);
        return $this->formatOutput($token);
    }

    public function qiniuFileCallback(Request $request)
    {
        $params = $request->all();
//        $_body = file_get_contents('php://input');
//        info('七牛文件上传回调参数', [$_body]);//七牛的回调比较奇葩，这是原生方法json_decode($_body)，但中文文件名会转码
//        $params = json_decode($_body, true);
        info('七牛文件上传文件回调参数', $params);
        $fkey  = data_get($params, 'fkey','');
        $uid   = data_get($params, 'uid',0);
        $group_id = data_get($params,'group_id', 0);
        $typeId = data_get($params,'type_id', 0);
        $cloud_name = 'http://cdn.rockysports.cn/'.$fkey;
        //todo photo create
        if ($group_id > 0) {
            $cloud_name = 'http://cdn2.91haoka.cn/'.$fkey;
            $size = data_get($params, 'size', 0);
            // if(empty($size)){
            //    $imageInfo = $cloud_name.'?imageInfo';
            //    $response = WatermarkController::get($imageInfo);
            //    $obj = json_decode($response, true);
            //    $size = data_get($obj, 'size', '');
            // }
            // $imageInfo = $cloud_name.'?exif';
            // $response = WatermarkController::get($imageInfo);
            // $obj = json_decode($response, true);
            // $DateTime = data_get($obj, 'DateTime', '');
            // $shooting_time = data_get($DateTime, 'val', '');
    
            $id = \DB::table('files')->insertGetId([
                'name'=>data_get($params,'name',''),
                'type_id'=>$typeId,
                'user_id'=>$uid,
                'group_id'=>$group_id,
                'quality'=>data_get($params,'quality',''),
                'size'=>data_get($params,'size',''),
                'cloud_name'=>$cloud_name,
                'local_name'=>$fkey,
                // 'shooting_time'=>$shooting_time,
                'created_at'=>date('Y-m-d H:i:s'),
            ]);
            
            // $isMatched = preg_match('/[.]mp/', $cloud_name, $matches);
            // if (!$isMatched) {
            //     $width = 1280;
            //     $to = $cloud_name . '?imageMogr2/auto-orient/thumbnail/' . $width . 'x/strip';
            //     $thumb = SportService::upload2Qiniu($to, 'wq113');
            //     Files::where('id', $id)->update(['thumb_750' => $thumb,'status'=>100]);
            // }
        }


//        $key = '6UAIrL0G0kUnqqvGru3b9Hsm';
//        $secret_key = '4PSeCZqBResRRsEZHYjPtXtBHtyXwzxv';
//        $aip = new AipFace(21926928,$key,$secret_key);
//        $res = $aip->addUser($cloud_name,'URL',$group_id,$p_id);
        //\DB::table('photo_types')->insert(['photo_id'=>$p_id,'type'=>data_get($params,'type',0)]);
        return $this->formatOutput([
            'fkey' => $fkey,
        ]);
    }

    public function miniappUrl(Request $request)
    {
        $params = $request->all();
        $appId = data_get($params, 'app_id', config('payment.jueqiweilaixcx.wechat.app_id'));
        $path = data_get($params, 'path', '');
        $secret = '';
        if ($appId == config('payment.jueqiweilaixcx.wechat.app_id')) {
            $secret = config('payment.jueqiweilaixcx.wechat.app_secret');
        }
        $wechat  = new WechatService($appId, $secret);
        $r = $wechat->urlscheme($path);
        $j = json_decode($r, 1);

        return $this->formatOutput([
            'openlink' => data_get($j, 'openlink', ''),
        ]);
    }

    public function miniappCodeUnlimit(Request $request)
    {
        $params = $request->all();
        $appId = data_get($params, 'app_id', config('payment.jueqiweilaixcx.wechat.app_id'));
        $path = data_get($params, 'path', '');
        $secret = '';
        if ($appId == config('payment.jueqiweilaixcx.wechat.app_id')) {
            $secret = config('payment.jueqiweilaixcx.wechat.app_secret');
        }
        $wechat  = new WechatService($appId, $secret);
        $r = $wechat->getUnlimited($path, 'release');

        if (!is_dir(public_path('storage/tmp'))) {
            mkdir(public_path('storage/tmp'));
        }
        if (!is_dir(public_path('storage/tmp/shareCode'))) {
            mkdir(public_path('storage/tmp/shareCode'));
        }

        $rand = str_random(10).'.jpg';
        $filename = public_path('storage/tmp/shareCode').'/'.$rand;
        file_put_contents($filename, $r);

//        $f = upload2Qiniu($filename);

        return $this->formatOutput(['img' => env('APP_URL').'/storage/tmp/shareCode/'.$rand]);

    }

    public function miniappMsgCheck(Request $request)
    {
        $params = $request->all();

        $user = authUser();


    }
}
